<template>
	<!-- 稳定版本 -->
	<view class="default-show" @click="defaultShow=true" v-if="!defaultShow">
		<image src="../../static/d.jpg" mode=""></image>
	</view>
	<view v-else>
		<view v-if="show">
			<Header></Header>
			<view class="content-box">
				<view class="ava">
					<image class="avatar" src="../../static/userCode.png" mode=""></image>
				</view>
				<view class="cardNum">
					<view class="school-name">{{info.organizationName||''}}</view>
					<view class="label-box">
						<image src="../../static/icon/icon_class.png" class="icon-logo"></image>
						<view class="right-ipt" v-if="gradeid" style="width: 554upx;">{{info.gradeName||''}}</view>
						<view class="right-ipt" @click="showSelector" v-else style="width: 554upx;">
							<view>{{className}}</view>
							<image src="../../static/img/go.png" mode=""></image>
						</view>
					</view>
					<view class="label-box">
						<image src="../../static/icon/icon_username.png" class="icon-logo"></image>
						<input class="right-ipt" v-model="childName" type="text" placeholder="请输入学生姓名或者别名" placeholder-style="font-size: 26rpx;color: #999" /> 
					</view>
				</view>
				
				<view class="btn-box">
					<!-- <button type="primary" class="button submit" open-type='getPhoneNumber' @getphonenumber="getPhoneNumber" v-if="agree">授权</button>
					<button type="primary" class="button submit" @click="showErrToast('请先同意用户协议')" v-else>授权</button> -->
					<!-- <button type="primary" class="button submit" @click="showPrivacyMask=true" v-if="agree">授权</button> -->
					<button type="primary" class="button submit" @click="showErrToast('请先勾选用户协议')" v-if="!agree">注册</button>
					<button class="button submit" id="agree-btn" open-type="getPhoneNumber|agreePrivacyAuthorization" @getphonenumber="getPhoneNumber" @agreeprivacyauthorization="handleAgree" v-else>注册</button>
					<navigator class="button cancellation" target="miniProgram" open-type="exit">取消</navigator>
				</view>
			</view>
		
			<!-- <view class="attention">
				点击授权表示您已同意<text @click="toagreement"style="color: #007AFF;">《用户服务协议》</text>
			</view> -->
			<view class="button-box" @click="agree=!agree">
				<view>
					<checkbox-group ><checkbox :checked="agree" style="transform:scale(0.8) ;"/></checkbox-group>
					<view  class="text" style="font3-size: 26upx;color: #909399;bottom: 50upx;">
						我已阅读并同意
						<text @click.stop="toagreement" style="color: #007AFF;">《用户服务协议》</text>
						<text @click.stop="openPrivacyContract" style="color: #007AFF;">，《隐私协议》</text>
					</view>
				</view>
			</view>
		
			<!-- 搜索框 -->
			<view v-show="showMark" class="zzc" @click.stop="close">
				<view @click.stop="">
					<view class="btn">
						<view @click="close">取消</view>
						<view @click="choose" style="color: #007AFF;">确定</view>
					</view>
					<view class="search">
						<input type="text" value="" v-model="word" placeholder="搜索" />
					</view>
					<view class="box">
						<picker-view class="picker-area" @pickstart="disable=true" @pickend="disable=false" @change="changeX">
							<picker-view-column>
								<view class="item" v-if="item.organizationName?item.organizationName.includes(word):false" v-for="(item,index) in list" :key="index">{{item.organizationName}}</view>
							</picker-view-column>
						</picker-view>
					</view>
				</view>
			</view>
			
			<view class="ws-privacy-popup" v-if="showPrivacyMask">
				<view class="ws-privacy-popup__header">
					<view class="ws-picker__title">{{ title }}</view>
				</view>
				<view class="ws-privacy-popup__container">
					<text>{{ desc }}</text>
					<text class="ws-privacy-popup__container-protocol" @click="openPrivacyContract">{{ protocol }}</text>
					<text>{{ subDesc }}</text>
				</view>
				<view class="ws-privacy-popup__footer">
					<button class="is-agree" id="agree-btn" open-type="getPhoneNumber|agreePrivacyAuthorization" @getphonenumber="getPhoneNumber" @agreeprivacyauthorization="handleAgree">同意并授权手机号</button>
					<button class="is-disagree" id="disagree-btn" @click="handleDisagree">不同意</button>
				</view>
			</view>
		</view>
	</view>
	
</template>

<script>
	var WXBizDataCrypt = require('@/utils/RdWXBizDataCrypt.js');
	export default {
		data() {
			return {
				defaultShow: true,
				agree: false,
				appId: getApp().globalData.appId,
				sessionkey: uni.getStorageSync('sk'),
				wxOpenId: uni.getStorageSync('openId'),
				pubopenid: '',
				gradeid: '',
				schoolId: '',
				info: '',
				newUser: false,
				childName: '',
				show: false,
				className: '请选择班级',
				list: [],
				
				// 搜索框
				showMark: false,
				disable: false,
				word: '',
				changeIndex: 0,
				
				// 隐私指引弹框
				showPrivacyMask: false,
				title: '用户隐私保护提示',
				desc: '感谢您使用本应用，您使用本应用的服务之前请仔细阅读并同意',
				protocol: '《用户隐私保护指引》',
				subDesc: '。如您同意，请点击【同意】开始使用',
				
			}
		},
		methods: {
			openPrivacyContract(){
				wx.openPrivacyContract({
					success: (res) => {
					},
				})
			},
			handleDisagree() {
				this.showPrivacyMask = false
			},
			handleAgree() {
				this.showPrivacyMask = false
			},
			showErrToast(title){
				uni.showToast({
					icon: 'none',
					title: title
				})
			},
			login() {
				let that = this
				uni.login({
					success(res2) {
						that.getOpenId(res2.code)
					}
				})
			},
			getOpenId(code) {
				this.$http('/pay/api/wechart/getSessionNew', {
					code: code,
					appId: this.appId
				}, res3 => {
					this.wxOpenId = res3.data.openid
					this.sessionkey = res3.data.sk ? res3.data.sk : res3.data.session_key
					uni.setStorageSync('openId', res3.data.openid)
					uni.setStorageSync('sk', res3.data.sk)
					if (this.gradeid) this.getOrganizationId()
					else this.getClassList()
				}, 'GET')
			},
			getClassList() {
				this.$http('/member/api/organization/list', {
					"condition": { "parentId": this.schoolId },
				}, res => {
					this.list = res.data.items
					this.getOrganizationId()
				})
			},
			getOrganizationId() {
				this.$http('/minprogram/api/member/GetOrganizationInfoByGrade', {
					"schoolId": this.schoolId,
					"gradeId": this.gradeid,
					"openId": this.wxOpenId
				}, res => {
					this.info = res.data
					this.getLogin()
				}, 'GET')
			},
			getLogin() {
				uni.hideLoading()
				this.$http('/minprogram/api/member/verify', {
					"wxOpenId": uni.getStorageSync('openId'),
					"pubOpenId": this.pubopenid
				}, res4 => {
					uni.setStorageSync('token', res4.data.token)
					if (this.info.faceCount > 0) uni.reLaunch({ url: '/pages/index/index?type=2' })
					else this.show = true
				}, 'POST', () => {
					uni.hideToast()
					this.newUser = true
					this.show = true
				})
			},
			async getPhoneNumber(e) {
				let that = this
				if (e.detail.errMsg == "getPhoneNumber:fail user deny") { //用户决绝授权  
				} else {

					var pc = new WXBizDataCrypt(this.appId, this.sessionkey);
					var data = pc.decryptData(e.detail.encryptedData, e.detail.iv)

					if (this.newUser) {

						await new Promise((aaa, bbb) => {
							this.$http('/minprogram/api/member/bind', {
								"wxOpenId": this.wxOpenId,
								"phone": data.phoneNumber,
								"wxName": data.phoneNumber,
								"pubOpenId": this.pubopenid
							}, result => {
								uni.setStorageSync('token', result.data.token)
								aaa()
							})
						})
						this.newUser = false
					}

					this.$http('/minprogram/api/member/getStudentInfo', {
						"ownerName": this.childName.trim(),
						"schoolId": this.schoolId,
						"gradeId": this.gradeid ? this.gradeid : this.info.gradeId,
					}, res => {
						if (res.data.phone) {
							if (res.data.phone == data.phoneNumber) {

								uni.reLaunch({
									url: '/pages/index/index?type=2'
								})

							} else {
								if (res.data.isSign) {

									uni.showToast({
										title: '该学生已签约',
										icon: 'none'
									})
								} else {
									uni.showModal({
										content: '已绑定的号码为初始号码，请修改为家长自己的手机号码。',
										cancelText: '我知道了',
										confirmText: '立即修改',
										success: function(suc) {
											if (suc.confirm) {
												uni.navigateTo({
													url: `/pages/changePhone/changePhone?oldPhone=${res.data.phone}&newPhone=${data.phoneNumber}&ownerName=${that.childName.trim()}&gradeId=${that.gradeid?that.gradeid:that.info.gradeId}&organizationId=${that.schoolId}&id=${res.data.id}&schoolName=${that.info.organizationName}&className=${that.gradeid?that.info.gradeName:that.className}`
												})
											} else if (suc.cancel) {
											}
										}
									});
								}

							}
						} else this.addFace()
					}, 'GET')

				}
			},
			// d53bfe79-8072-40cc-42a8-08d91b2fceaf
			change(e) {
				this.className = this.list[e].organizationName
				this.info.gradeId = this.list[e].id
			},
			addFace() {
				this.$http('/minprogram/api/member/saveOwnerStudent', {
					"ownerName": this.childName.trim(),
					"organizationId": this.schoolId,
					"gradeId": this.gradeid ? this.gradeid : this.info.gradeId,
				}, res => {
					if (res.data.value) {
						uni.reLaunch({ url: '/pages/index/index?type=2' })
					}
				})
			},
			toagreement() {
				uni.navigateTo({ url: '/pages/agreement/agreement' })
			},

			// 搜索框
			close() {
				if (this.disable) return;
				this.showMark = false
			},
			choose() {
				if (this.disable) return;
				if (this.word) {
					let nameList = this.list.map((item) => {
						return item.organizationName;
					})
					let searchList = nameList.filter((item) => { if (item.includes(this.word)) return item })
					if (searchList.length > 0) { this.change(nameList.indexOf(searchList[this.changeIndex])) }
				} else { this.change(this.changeIndex) }
				this.showMark = false
			},
			changeX(e) {
				if (this.changeIndex != e.detail.value[0]) { this.changeIndex = e.detail.value[0] }
				this.disable = false
			},
			showSelector(index) {
				if (this.curIndex != index) {
					this.word = '随便写个什么反正是重置picker-view'
					this.$nextTick(() => {
						this.curIndex = index
						this.word = ''
					})
				}

				this.$nextTick(() => { this.showMark = true })
			},

			// 提取所有参数
			queryParse(url) {
				var paramObj = {};
				if (url.indexOf('?') > -1) {
					var _url = url.split('?')[1].split('#')[0];
					var strArr = _url.split('&');
					strArr.forEach(ele => {
						var key = ele.split('=')[0];
						var val = ele.split('=')[1];
						paramObj[key] = val;
					});

				}
				return paramObj;
			},
		},
		onLoad(e) {
			// 搜索框---------------
			// this.getClassList()
			// 搜索框---------------
			uni.showLoading()
			if (e.pubopenid) {
				this.pubopenid = e.pubopenid
				this.schoolId = e.schoolId
				this.gradeid = e.gradeid || ''
				uni.setStorageSync('pubopenid', e.pubopenid)
				this.login()
			}

			// 二维码扫码进入场景传译
			if (e.q) {
				const values = decodeURIComponent(e.q)
				const params = this.queryParse(values)
				this.pubopenid = params.pubopenid
				this.schoolId = params.schoolId
				this.gradeid = params.gradeid
				uni.setStorageSync('pubopenid', e.pubopenid)
				this.login()
			}
			
			wx.getPrivacySetting({
				success:res=>{
					this.protocol = res.privacyContractName
				}
			})
			// ········································
			// this.schoolId = e.schoolId
			// this.login()
			// ········································
			
			
			
			//--------------------------------------------------------------------------
			// this.show = true
			
			//--------------------------------------------------------------------------
		}
	}
</script>

<style scoped lang="less">
	.default-show{
		width: 100vw;
		height: 100vh;
		image{
			width: 100%;
			height: 100%;
		}
	}
	.content-box{
		margin: 106upx 30upx 0;
		position: relative;
		background: rgba(255, 255, 255, .3);
		border-radius: 16upx;
		padding: 100upx 20upx 10upx;
		.ava{
			position: absolute;
			left: 50%;
			top: -60upx;
			margin-left: -60upx;
			width: 120upx;
			height: 120upx;
			border-radius: 50%;
			padding: 10upx;
			background: #fff;
			.avatar{
				width: 100%;
				height: 100%;
			}
		}
		.cardNum{
			background: #fff;
			border-radius: 16upx;
			padding: 20upx 30upx;
			margin-bottom: 20upx;
			box-shadow: 0 3upx 20upx 1upx rgba(216, 240, 237, 1.0);
			.school-name{
				margin: 16upx 0 36upx 10upx;
			}
			.label-box{
				display: flex;
				align-items: center;
				height: 88upx;
				margin-bottom: 22upx;
				.icon-logo{
					width: 56upx;
					height: 56upx;
					margin-right: 16upx;
				}
				.right-ipt{
					width: 520upx;
					background: #f2f2f2;
					height: 70upx;
					display: flex;
					align-items: center;
					padding: 0 10upx;
					font-size: 26upx;
					color: #999;
					border-radius: 6upx;
					justify-content: space-between;
					image{
						transform: rotate(90deg);
						width: 20upx;
						height: 20upx;
						margin-right: 12upx;
					}
				}
			}
		}
		.btn-box{
			background: #fff;
			border-radius: 16upx;
			padding: 30upx;
			box-shadow: 0 3upx 20upx 1upx rgba(216, 240, 237, 1.0);
			.button{
				width: 100%;
				height: 88upx;
				text-align: center;
				line-height: 88upx;
				border-radius: 10upx;
				font-size: 28upx;
			}
			.button~.button{
				margin-top: 20upx;
			}
			.submit{
				background: #49b9ad;
				color: #fff;
			}
			.cancellation{
				background: #e4e4e4;
				color: #6a6a6a;
			}
		}
	}
	.attention{
		font-size: 24upx;
		color: #909399;
		position: fixed;
		bottom: 20upx;
		width: 100%;
		text-align: center;
	}
	.button-box {
		width: 700upx;
		margin: 20upx auto;
		border-radius: 20upx;
		box-sizing: border-box;
		padding: 8upx 0;
		>view {
			font-size: 26upx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}
	}
	
	.zzc{
		width: 100vw;
		height: 100vh;
		position: fixed;
		top: 0;
		background-color: rgba(0,0,0,0.4);
		z-index: 100;
		>view{
			width: 100%;
			height: 700upx;
			background-color: #FFFFFF;
			position: absolute;
			bottom: 0;
			box-sizing: border-box;
			>view.btn{
				width: 100%;
				height: 80upx;
				display: flex;
				justify-content: space-between;
				// border-bottom: 1upx solid #dddddd;
				>view{
					height: 100%;
					width: 160upx;
					font-size: 24upx;
					line-height: 80upx;
					text-align: center;
					color: #999999;
				}
			}
			>view.search{
				width: 100%;
				>input{
					background-color: #eeeeee;
					width: 90%;
					margin: 0 auto;
					height: 70upx;
					border-radius: 10upx;
					text-align: center;
				}
			}
			>view.box{
				width: 100%;
				height: 100%;
				box-sizing: border-box;
				padding: 20upx 0;
				.picker-area{
				        width: 100%;
				        height: 100%;
						text-align: center;
				    }
				.item{
					line-height: 34px;
				}
			}
		}
	}
	
</style>